package com.medicine.sys.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.medicine.common.exception.WarnException;
import com.medicine.sys.bean.UserForm;
import com.medicine.sys.dto.UserDTO;
import com.medicine.sys.entity.*;
import com.medicine.sys.mapper.UserMapper;
import com.medicine.sys.param.UserParam;
import org.apache.commons.beanutils.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.lang.reflect.InvocationTargetException;

@Service
@Transactional
public class UserService extends ServiceImpl<UserMapper, User> {

    @Autowired
    private UserDepartmentService userDepartmentService;

    @Autowired
    private UserRoleService userRoleService;


    public IPage<UserDTO> selectList(UserParam userParam){
        Page<UserDTO> userPage = new Page<>(userParam.getPage(),userParam.getSize());
        return this.baseMapper.pageList(userPage,userParam.getName(),userParam.getUserName(),userParam.getPhone());
    }

    public void install(UserForm userForm) throws Exception {

        User user;
        user = getUserName(userForm.getUserName());
        if(user!=null){
            throw new WarnException("用户名已存在！");
        }
        user = new User();
        BeanUtils.copyProperties(user,userForm);

        saveOrUpdate(user);

        UserDepartment userDepartment = new UserDepartment();
        userDepartment.setDepartmentId(userForm.getDepartmentId());
        userDepartment.setUserId(user.getId());
        userDepartmentService.install(userDepartment);

        UserRole userRole = new UserRole();
        userRole.setRoleId(userForm.getRoleId());
        userRole.setUserId(user.getId());
        userRoleService.install(userRole);

    }


    public UserDTO getId(String id) throws Exception {

        UserDTO userDTO = new UserDTO();
        Department department = userDepartmentService.getOneUserId(id);
        if(department !=null){
            userDTO.setDepartmentId(department.getId());
            userDTO.setDepartmentName(department.getName());
        }
        Role role = userRoleService.getOneUserId(id);
        if(role !=null){
            userDTO.setRoleId(role.getId());
            userDTO.setRoleName(role.getName());
        }
        User user = getById(id);
        if (user == null) {
            throw new WarnException("不存在");
        }
        BeanUtils.copyProperties(user,userDTO);
        return userDTO;
    }

    public User getUserName(String userName){
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.eq("user_name",userName);
        return getOne(queryWrapper);
    }

}
